package com.cheyunkeji.er.fragment.evaluate;

import android.content.Intent;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.activity.evaluate.CustomerCameraActivity;
import com.cheyunkeji.er.activity.evaluate.EvaluateWorkflowActivity;
import com.cheyunkeji.er.activity.evaluate.PhotoPreViewActivity;
import com.cheyunkeji.er.base.BaseFragment;
import com.cheyunkeji.er.bean.evaluate.EvaluateDetailResult2;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.service.OssService;
import com.cheyunkeji.er.utils.ImageLoadUtil;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.evaluate.CameraSelectDialog;
import com.cheyunkeji.er.view.evaluate.ImageSelectDialog;
import com.cheyunkeji.er.view.evaluate.TakePhotoDisplayView;
import com.google.gson.Gson;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.utils.ImageCaptureManager;
import okhttp3.Call;
import okhttp3.Request;

import static android.app.Activity.RESULT_OK;

/** Created by Michael on 2017/3/29 14:26. */
public class TakeCarPhotoFragment extends BaseFragment
    implements CameraSelectDialog.MultiClickActionListener,
        EvaluateWorkflowActivity.OnOutActionListener,
        TakePhotoDisplayView.OnTakePhotoListener,
        ImageSelectDialog.ImageSelectListener {

  public static final int PAGE_INDEX = 3;
  private static final String TAG = TakeCarPhotoFragment.class.getSimpleName();
  private static final int PREVIEW_IMG_REQUEST = 0x110;
  private static final int TAKE_PHOTO_WITH_CUSTOMIZED_CAMERA = 0x120;

  @BindView(R.id.tv_previous_step)
  TextView tvPreviousStep;

  @BindView(R.id.tv_next_step)
  TextView tvNextStep;

  @BindView(R.id.ll_bottom_view)
  LinearLayout llBottomView;

  @BindView(R.id.tpdv_01)
  TakePhotoDisplayView tpdv01;

  @BindView(R.id.tpdv_02)
  TakePhotoDisplayView tpdv02;

  @BindView(R.id.tpdv_03)
  TakePhotoDisplayView tpdv03;

  @BindView(R.id.tpdv_04)
  TakePhotoDisplayView tpdv04;

  @BindView(R.id.tpdv_05)
  TakePhotoDisplayView tpdv05;

  @BindView(R.id.tpdv_06)
  TakePhotoDisplayView tpdv06;

  @BindView(R.id.tpdv_07)
  TakePhotoDisplayView tpdv07;

  @BindView(R.id.tpdv_08)
  TakePhotoDisplayView tpdv08;

  @BindView(R.id.tpdv_09)
  TakePhotoDisplayView tpdv09;

  @BindView(R.id.tpdv_10)
  TakePhotoDisplayView tpdv10;

  @BindView(R.id.tpdv_11)
  TakePhotoDisplayView tpdv11;

  @BindView(R.id.tpdv_12)
  TakePhotoDisplayView tpdv12;

  @BindView(R.id.tpdv_13)
  TakePhotoDisplayView tpdv13;

  @BindView(R.id.tpdv_14)
  TakePhotoDisplayView tpdv14;

  @BindView(R.id.tpdv_15)
  TakePhotoDisplayView tpdv15;

  @BindView(R.id.tpdv_16)
  TakePhotoDisplayView tpdv16;

  @BindView(R.id.tpdv_17)
  TakePhotoDisplayView tpdv17;

  @BindView(R.id.tpdv_18)
  TakePhotoDisplayView tpdv18;

  @BindView(R.id.tpdv_19)
  TakePhotoDisplayView tpdv19;

  @BindView(R.id.tpdv_20)
  TakePhotoDisplayView tpdv20;

  @BindView(R.id.ll_last_photo)
  LinearLayout llLastPhoto;

  @BindView(R.id.iv_goto_top)
  ImageView ivGotoTop;

  @BindView(R.id.sv_content)
  ScrollView svContent;

  @BindView(R.id.rl_content)
  RelativeLayout rlContent;

  private int uploadImgCounter = 0;
  //    照片选择Dialog
  private CameraSelectDialog dialog;
  private ImageSelectDialog imgSelectDialog;
  private ArrayList<TakePhotoDisplayView> photoViewList;
  private ImageCaptureManager captureManager;

  //   图片上传具体图片对应的key
  private String[] imgPathKey =
      new String[] {
        "clzqb", "clzqf", "clyhb", "clzhf", "ybtczg", "qpzy", "hpzy", "zkt", "yb", "fdjc", "clmp",
        "clzp1", "clzp2", "clzp3", "clzp4", "clzp5", "clzp6", "clzp7", "clzp8", "clzp9"
      };
  private Runnable mTask;
  private HashMap<String, String> imgParams;

  @Override
  protected void doInflaterView(LayoutInflater inflater, ViewGroup container) {
    contentView = inflater.inflate(R.layout.er_frag_take_car_photo_layout, container, false);
    ButterKnife.bind(this, contentView);
  }

  @Override
  protected void init() {

    captureManager = new ImageCaptureManager(getActivity());
    dialog = new CameraSelectDialog(getActivity(), "", this, 0);
    dialog.setCanceledOnTouchOutside(false);
  }

  @Override
  protected void initView() {

    photoViewList = new ArrayList<>(20);
    photoViewList.add(tpdv01);
    photoViewList.add(tpdv02);
    photoViewList.add(tpdv03);
    photoViewList.add(tpdv04);
    photoViewList.add(tpdv05);
    photoViewList.add(tpdv06);
    photoViewList.add(tpdv07);
    photoViewList.add(tpdv08);
    photoViewList.add(tpdv09);
    photoViewList.add(tpdv10);
    photoViewList.add(tpdv11);
    photoViewList.add(tpdv12);
    photoViewList.add(tpdv13);
    photoViewList.add(tpdv14);
    photoViewList.add(tpdv15);
    photoViewList.add(tpdv16);
    photoViewList.add(tpdv17);
    photoViewList.add(tpdv18);
    photoViewList.add(tpdv19);
    photoViewList.add(tpdv20);

    for (int i = 0; i < photoViewList.size(); i++) {
      photoViewList.get(i).setListener(this);
    }

    tvPreviousStep.setOnClickListener(this);
    tvNextStep.setOnClickListener(this);
    ivGotoTop.setOnClickListener(this);
  }

  @Override
  protected void initData() {

    if (null != MyApplication.getInstance().getEvaluateResult()
        && null != MyApplication.getInstance().getEvaluateResult().getImage()) {

      EvaluateDetailResult2.ImageBean imgBean =
          MyApplication.getInstance().getEvaluateResult().getImage();

      ArrayList<String> tempImgPath = new ArrayList<>();

      tempImgPath.add(imgBean.getClzqb());
      tempImgPath.add(imgBean.getClzqf());
      tempImgPath.add(imgBean.getClyhb());
      tempImgPath.add(imgBean.getClzhf());
      tempImgPath.add(imgBean.getYbtczg());
      tempImgPath.add(imgBean.getQpzy());
      tempImgPath.add(imgBean.getHpzy());
      tempImgPath.add(imgBean.getZkt());
      tempImgPath.add(imgBean.getYb());
      tempImgPath.add(imgBean.getFdjc());
      tempImgPath.add(imgBean.getClmp());
      tempImgPath.add(imgBean.getClzp1());
      tempImgPath.add(imgBean.getClzp2());
      tempImgPath.add(imgBean.getClzp3());
      tempImgPath.add(imgBean.getClzp4());
      tempImgPath.add(imgBean.getClzp5());
      tempImgPath.add(imgBean.getClzp6());
      tempImgPath.add(imgBean.getClzp7());
      tempImgPath.add(imgBean.getClzp8());
      tempImgPath.add(imgBean.getClzp9());

      for (int i = 0; i < photoViewList.size(); i++) {

        if (!TextUtils.isEmpty(tempImgPath.get(i))) {

          ImageLoadUtil.loadImgInFrag(
              this, tempImgPath.get(i), photoViewList.get(i).getImageView());
          photoViewList.get(i).setImgPath(tempImgPath.get(i));
          photoViewList.get(i).setPhotoBtnState(true);
        }
      }
    }
  }

  private void showTakePhotoDialog(String titleDesc) {
    dialog.show();
    dialog.setTitle(titleDesc);
  }

  @Override
  public void onClick(View v) {
    super.onClick(v);

    switch (v.getId()) {
      case R.id.tv_next_step:
        onSaveEvaluateResult(
            new Runnable() {
              @Override
              public void run() {
                goToNextPage();
              }
            });
        break;
      case R.id.tv_previous_step:
        onSaveEvaluateResult(
            new Runnable() {
              @Override
              public void run() {
                goToPreviousPage();
              }
            });
        break;
      case R.id.iv_goto_top:
        svContent.smoothScrollTo(0, 0);
        break;
      default:
        break;
    }
  }

  @Override
  public void onCustomizeCameraSelected() {
    Intent intent = new Intent(getActivity(), CustomerCameraActivity.class);
    intent.putExtra("TAKE_PHOTO_SIGHT", (int) rlContent.getTag());
    startActivityForResult(intent, TAKE_PHOTO_WITH_CUSTOMIZED_CAMERA);
  }

  @Override
  public void onSystemCameraSelected() {
    openSystemCamera();
  }

  @Override
  public void onGallerySelected() {
    pickPhoto();
  }

  private void openSystemCamera() {
    Intent intent = null;
    try {
      intent = captureManager.dispatchTakePictureIntent();
      startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void onSaveEvaluateResult(Runnable task) {

    if (null != task) {
      this.mTask = task;
    }

    showDialog();

    /**
     * 选择图片并上传 1.判断图片是否是本地图片（不以 http 开头） 2.用 OssService.OssUnit 内部类去封装一个发射事件， OssUnit
     * 包含两个字段，一个是选中的本地图片的路径，另一个是显示图片的控件的下标 3.待图片上传成功后，OssUnit 路径替换成 OSS 云端图片的路径
     */
    Observable.create(
            new ObservableOnSubscribe<OssService.OssUnit>() {
              @Override
              public void subscribe(ObservableEmitter<OssService.OssUnit> emitter)
                  throws Exception {

                for (int i = 0; i < photoViewList.size(); i++) {
                  String tempPath = photoViewList.get(i).getImagePath();
                  if (!TextUtils.isEmpty(tempPath) && !tempPath.startsWith("http")) {
                    emitter.onNext(
                        new OssService.OssUnit(
                            photoViewList.get(i).getImagePath(),
                            photoViewList.get(i).getItemIndex()));
                  }
                }
                emitter.onComplete();
              }
            })
        .map(
            new Function<OssService.OssUnit, OssService.OssUnit>() {
              @Override
              public OssService.OssUnit apply(OssService.OssUnit ossUnit) throws Exception {

                return MyApplication.getInstance()
                    .getOssService(null)
                    .synchronizePutImage(
                        OssService.getOssObjectInfo(true), ossUnit.getPath(), ossUnit.getTag());
              }
            })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            new Observer<OssService.OssUnit>() {
              @Override
              public void onSubscribe(Disposable d) {
                Log.e(TAG, "onSubscribe: ");
              }

              @Override
              public void onNext(OssService.OssUnit ossUnit) {
                Log.e(TAG, "onNext: " + ossUnit.toString());
                photoViewList.get((Integer) ossUnit.getTag()).setImgPath(ossUnit.getPath());
              }

              @Override
              public void onError(Throwable e) {
                dismissDialog();
                //                      网络错误
                if (e instanceof ClientException) {
                  Toast.makeText(
                          TakeCarPhotoFragment.this.getActivity(), "请检查网络连接", Toast.LENGTH_SHORT)
                      .show();
                  return;
                }
                Toast.makeText(
                        TakeCarPhotoFragment.this.getActivity(), "图片上传失败", Toast.LENGTH_SHORT)
                    .show();
              }

              @Override
              public void onComplete() {
                dismissDialog();
                saveData();
              }
            });
  }

  /**
   * 图标按钮点击回调
   *
   * @param itemIndex
   */
  @Override
  public void takePhoto(int itemIndex) {

    Log.e(TAG, "takePhoto: " + itemIndex);

    rlContent.setTag(itemIndex);

    if (!TextUtils.isEmpty(photoViewList.get(itemIndex).getImagePath())) {

      //          有照片，预览照片
      Intent intent = new Intent(getActivity(), PhotoPreViewActivity.class);
      intent.putExtra("IMG_PATH", photoViewList.get(itemIndex).getImagePath());
      this.startActivityForResult(intent, PREVIEW_IMG_REQUEST);
    } else {

      Log.e(TAG, "takePhoto: TextDesc :  " + photoViewList.get(itemIndex).getTextDesc());

      if (itemIndex < 4)

        //              1-4 弹出 系统/挡牌相机选择弹框
        showTakePhotoDialog(photoViewList.get(itemIndex).getTextDesc());

      //            弹出 相机/相册选择照片对话框
      else {
        showImgSelectDialog(photoViewList.get(itemIndex).getTextDesc());
      }
    }
  }

  public void showImgSelectDialog(String titleStr) {

    if (null == imgSelectDialog) {
      imgSelectDialog = new ImageSelectDialog(this.getActivity(), this, titleStr);
    } else {
      imgSelectDialog.setTitleStr(titleStr);
    }
    imgSelectDialog.show();
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
      case PhotoPicker.REQUEST_CODE:
        if (data != null) {
          String localImgPath =
              data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS).get(0);
          if (!TextUtils.isEmpty(localImgPath)) {

            photoViewList.get((int) rlContent.getTag()).setImgPath(localImgPath);
            photoViewList.get((int) rlContent.getTag()).setPhotoBtnState(true);
            ImageLoadUtil.loadImgInFrag(
                this, localImgPath, photoViewList.get((int) rlContent.getTag()).getImageView());
          }
        }
        break;

      case ImageCaptureManager.REQUEST_TAKE_PHOTO:
        if (resultCode == RESULT_OK) {
          captureManager.galleryAddPic();

          String path = captureManager.getCurrentPhotoPath();
          Log.e(TAG, "onActivityResult: ImagePath : " + path);

          photoViewList.get((int) rlContent.getTag()).setImgPath(path);
          photoViewList.get((int) rlContent.getTag()).setPhotoBtnState(true);
          ImageLoadUtil.loadImgInFrag(
              this, path, photoViewList.get((int) rlContent.getTag()).getImageView());
        }

        break;

      case TAKE_PHOTO_WITH_CUSTOMIZED_CAMERA:
        if (resultCode == RESULT_OK) {

          String imgPath = data.getStringExtra("IMG_PATH");
          Log.e(TAG, "onActivityResult: " + imgPath);

          photoViewList.get((int) rlContent.getTag()).setImgPath(imgPath);
          photoViewList.get((int) rlContent.getTag()).setPhotoBtnState(true);
          ImageLoadUtil.loadImgInFrag(
              this, imgPath, photoViewList.get((int) rlContent.getTag()).getImageView());
        }

        break;

        //           删除照片
      case PREVIEW_IMG_REQUEST:
        if (data == null) {
          return;
        }

        boolean deleteImg = data.getBooleanExtra("DELETE_IMG", false);
        Log.e(TAG, "onActivityResult: " + deleteImg);

        if (deleteImg) {
          photoViewList.get((int) rlContent.getTag()).setImgPath("");
          photoViewList.get((int) rlContent.getTag()).setPhotoBtnState(false);
          photoViewList.get((int) rlContent.getTag()).getImageView().setImageDrawable(null);
        }
        break;

      default:
        break;
    }
  }

  /** 进入图片选择页面 */
  private void pickPhoto() {
    PhotoPicker.builder().setPhotoCount(1).start(getActivity(), TakeCarPhotoFragment.this);
  }

  /** 上传数据 */
  private void saveData() {

    HashMap<String, String> params = new HashMap<>();
    //      params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//
    // params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    params.put("aid", MyApplication.getInstance().getEvaluateResult().getAid());

    if (imgParams == null) {
      imgParams = new HashMap<>();
    }

    if (MyApplication.getInstance().getEvaluateResult() == null
        || MyApplication.getInstance().getEvaluateResult().getIroute() == null
        || MyApplication.getInstance().getEvaluateResult().getIroute().size() == 0) {
      int[] iroute = new int[15];
      iroute[PAGE_INDEX] = 1;
      String json = new Gson().toJson(iroute);
      Log.e(TAG, "saveData: 评估记录为空或数组为空时 保存记录数组 ：  " + json.substring(1, json.length() - 1));
      params.put("iroute", json.substring(1, json.length() - 1));
    } else {
      MyApplication.getInstance().getEvaluateResult().getIroute().set(PAGE_INDEX, 1);
      String json = new Gson().toJson(MyApplication.getInstance().getEvaluateResult().getIroute());
      params.put("iroute", json.substring(1, json.length() - 1));
      Log.e(
          TAG, "saveData:  保存记录数组 ：记录非空并且数组非空时 保存记录数组 ：   " + json.substring(1, json.length() - 1));
    }

    /** 设置图片上传参数 */
    for (int i = 0; i < photoViewList.size(); i++) {
      imgParams.put(imgPathKey[i], photoViewList.get(i).getImagePath());
    }

    String result = new Gson().toJson(imgParams);

    Log.e(TAG, "saveData: " + result);

    params.put("image", result);

    //        根据评估类型进行保存或编辑
    int evaluateType = ((EvaluateWorkflowActivity) getActivity()).getEvaluateArchiveType();

    //       保存新创建、未上传待评估数据
    if (evaluateType == Constants.ARCHIVE_TYPE_CREATE_NEW_EVALUATE
        || evaluateType == Constants.ARCHIVE_TYPE_UN_UPLOAD_TO_EVALUATE
        || evaluateType == Constants.ARCHIVE_TYPE_WITH_FAST_EVALUATE_VIN) {

      ApiClient.postForm(
          ((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(),
          params,
          new RespCallback<EvaluateDetailResult2>() {

            @Override
            protected void onRequestFailed(String msg) {
              SToast.show(msg);
              if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                mTask.run();
                mTask = null;
              }
            }

            @Override
            protected void onSuccess(EvaluateDetailResult2 data) {
              if (null != data) {
                MyApplication.getInstance().setEvaluateResult(data);
                if (null != mTask) {
                  mTask.run();
                  mTask = null;
                }
              }
            }

            @Override
            public void onBefore(Request request, int id) {
              //                    showDialog();
            }

            @Override
            public void onAfter(int id) {

              Log.e(TAG, "onAfter: 是否在主线程 ： " + (Looper.getMainLooper() == Looper.myLooper()));

              //                    TakeCarPhotoFragment.this.getActivity().runOnUiThread(new
              // Runnable() {
              //                        @Override
              //                        public void run() {
              //                            dismissDialog();
              //                        }
              //                    });
            }
          });

    } else if (evaluateType == Constants.ARCHIVE_TYPE_UPLOADED_TO_EDIT) {

      ApiClient.postForm(
          ((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(),
          params,
          new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

              // 网络异常
              if (e instanceof UnknownHostException || e instanceof SocketException) {
                SToast.show(R.string.tip_network_error, Gravity.CENTER);
                return;
              }
            }

            @Override
            public void onResponse(String response, int id) {

              try {

                JSONObject obj = new JSONObject(response);
                if (obj.optInt("code") == 1) {
                  //                            Log.e(TAG, "onResponse: 编辑成功 : " +
                  // obj.optString("data"));
                  if (null != mTask) {
                    mTask.run();
                    mTask = null;
                  }
                } else {
                  SToast.show(obj.optString("msg"));
                  if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                    mTask.run();
                    mTask = null;
                  }
                }

              } catch (JSONException e) {
                e.printStackTrace();
              }
            }

            @Override
            public void onBefore(Request request, int id) {
              //                    showDialog();
            }

            @Override
            public void onAfter(int id) {

              //                    TakeCarPhotoFragment.this.getActivity().runOnUiThread(new
              // Runnable() {
              //                        @Override
              //                        public void run() {
              //                            dismissDialog();
              //                        }
              //                    });
            }
          });
    }
  }

  private void goToNextPage() {
    ((EvaluateWorkflowActivity) getActivity()).setCurrentPage(CarFrameworkCheckFragment.PAGE_INDEX);
  }

  private void goToPreviousPage() {
    ((EvaluateWorkflowActivity) getActivity()).setCurrentPage(CarConfigInfoFragment.PAGE_INDEX);
  }

  @Override
  public void onTakePhotoWithSystemCamera() {
    openSystemCamera();
  }

  @Override
  public void onSelectImgOnGallery() {
    pickPhoto();
  }
}
